package com.bjtg.threegoclinet.operation;

import com.bjfl.saleManager.util.BaiduTTSSpeakUtil;
import com.bjtg.threegoclinet.MainActivity;
import com.bjtg.threegoclinet.bean.ConstValue;
import com.bjtg.threegoclinet.base.DoorType;
import com.bjtg.threegoclinet.bean.Constants;
import com.bjtg.threegoclinet.okhttpUtils.HttpConstants;
import com.bjtg.threegoclinet.okhttpUtils.OkHttpClientManager;
import com.bjtg.threegoclinet.receiver.ThreeGoReceiver;
import com.bjtg.threegoclinet.util.IsInternet;
import com.bjtg.threegoclinet.util.LattePreference;
import com.bjtg.threegoclinet.util.MediaPath;
import com.bjtg.threegoclinet.util.MediaPlayControl;
import com.event.OpenDoorType;
import com.bjfl.bean.GoodsLineMsg;
import com.log.LatteLogger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.bjtg.threegoclinet.MainActivity.eleLockDevice;
import static com.bjtg.threegoclinet.MainActivity.goodsDevice;
import static com.bjtg.threegoclinet.base.BaseActivity.PARAMMAP;
import static com.bjtg.threegoclinet.base.BaseActivity.context;

/**
 * Created by 86463
 * Created time: 2018/1/30/10:10
 */

public class DoorOperation {
    private static final String TAG = "operation";
    private static MediaPlayControl mediaPlayControl = MediaPlayControl.getInstance();
    private static ExecutorService executorService = Executors.newFixedThreadPool(4);

    /**
     * 开门方法入口
     *
     * @param scanId
     * @param scanType
     */
    public static void openDoor(final String scanId, final String scanType) {
        executorService.execute(() -> {
            int doorState = eleLockDevice.CheckEleLockState();
            if (doorState == 1) {
                int locFlag = getLocFlag();
                if (locFlag == 1) {
                    pullDoor(scanId, scanType);
                } else {
                    int lockOp = getLocFlag();
                    if (lockOp == 1) {
                        pullDoor(scanId, scanType);
                    }
                }
            } else {
                BaiduTTSSpeakUtil.getInstance().speak("对不起，门锁故障，请选择其它自助售货机购买商品");
                ThreeGoReceiver.resetOpenDoorTime();
            }

        });


    }

    private static void pullDoor(String scanId, String scanType) {
        // 检查用户是否拉开柜门
        int doorSuccessFlag = checkDoorState(scanId, scanType);
        if (doorSuccessFlag == 1) {
            //开门成功
            PARAMMAP.put("openStatus", "1");
            postOpenDoorMsg(scanId);
            autoCloseDoorNew(scanId, scanType);
        } else {
            LatteLogger.i("非正常流程", "error");
            LattePreference.addUserId(LattePreference.USER_ID, "1");
        }
    }

    /**
     * 发送开门反馈信息
     *
     * @param scanId
     */
    private static void postOpenDoorMsg(String scanId) {
        //开锁成功
        PARAMMAP.put("id", scanId);
        if (ThreeGoReceiver.type.equals(OpenDoorType.BUYER.getType())) {
            PARAMMAP.put("scanStatus", "1");
        } else {
            PARAMMAP.put("scanStatus", "0");
        }

        if (ThreeGoReceiver.type.equals(OpenDoorType.BUYER.getType())) {
            if (IsInternet.checkNetwork(context)) {
                postUserOpenMsg();
            } else {
                rePostUserOpenDoorMsg();

            }

        } else {
            if (IsInternet.checkNetwork(context)) {
                postOpeOpenDoor();
            } else {
                //没网络情况下，每隔1s检测一次网络状态
                rePostOpOpenDoorMsg();

            }
        }

    }

    /**
     * 每隔一秒检测一次网络状态，直至运维人员开门反馈发送成功
     */
    private static void rePostOpOpenDoorMsg() {
        executorService.execute(() -> {
            try {
                while (true) {
                    if (IsInternet.checkNetwork(context)) {
                        postOpeOpenDoor();
                        break;
                    }
                    Thread.sleep(1000);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 每隔一秒检测一次网络状态，直至用户开门反馈发送成功
     */
    private static void rePostUserOpenDoorMsg() {
        executorService.execute(() -> {
            try {
                while (true) {
                    if (IsInternet.checkNetwork(context)) {
                        postUserOpenMsg();
                        break;
                    }
                    Thread.sleep(1000L);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });
    }

    /**
     * 发送运维人员开门反馈
     */
    private static void postOpeOpenDoor() {
        OkHttpClientManager.getInstance().postAsync(Constants.getStaffscan(),
                HttpConstants.feedback, PARAMMAP, new OkHttpClientManager.HttpCallback() {
                    @Override
                    public void onSuccess(String result, int code) {
                        LatteLogger.d("opmsg", "开锁成功:" + PARAMMAP.toString());
                    }

                    @Override
                    public void onStart(int code) {

                    }

                    @Override
                    public void onFailure(int code) {

                    }

                });
    }

    /**
     * 发送用户开门反馈
     */
    private static void postUserOpenMsg() {
        OkHttpClientManager.getInstance().postAsync(Constants.getFeedback(),
                HttpConstants.feedback, PARAMMAP, new OkHttpClientManager.HttpCallback() {
                    @Override
                    public void onSuccess(String result, int code) {
                        LatteLogger.d("opmsg", "开锁成功:" + PARAMMAP.toString());
                    }

                    @Override
                    public void onStart(int code) {

                    }

                    @Override
                    public void onFailure(int code) {

                    }
                });
    }

    /**
     * 自动关门方法
     *
     * @param scanId
     * @param scanType
     */
    private static void autoCloseDoorNew(String scanId, String scanType) {
        int eleLockState; //关门成功
        try {
            while (true) {
                speakOpenStr();
                //查询微动开关状态
                eleLockState = MainActivity.eleLockDevice.CheckEleLockState();
                LatteLogger.d("当前状态3", "" + eleLockState);
                if (eleLockState == 1) {
                    Thread.sleep(500);
                    //微动开关被触发
                    if (ConstValue.DOORTYPE.equals(DoorType.SINGLEDOOR)) {
                        int lockState = MainActivity.eleLockDevice.OpenOrCloseLeftLock(2);
                        if (lockState != 1) {
                            autoCloseDoorNew(scanId, scanType);
                        }
                        LatteLogger.d("当前状态4", "" + eleLockState);
                    } else {
                        int leftLockState = MainActivity.eleLockDevice.OpenOrCloseLeftLock(2);
                        int rightLockState = MainActivity.eleLockDevice.OpenOrCloseRightLock(2);
                        if (leftLockState != 1 || rightLockState != 1) {
                            autoCloseDoorNew(scanId, scanType);
                        }
                    }
                    //返回货道距离
                    String channelListStr = "";
                    List<GoodsLineMsg> goodsLineMsgList = new ArrayList<>();
                    channelListStr = getLineString(scanId, channelListStr);
                    //反馈关门信息
                    LatteLogger.d("lineMsg", channelListStr);
                    postCloseDoorMsgMul(scanId, scanType, channelListStr);
                    break;
                }
                Thread.sleep(1000);
            }
            mediaPlayControl.play(MediaPath.closePath);
            isOpeSpeak = true;
        } catch (Exception ex) {
            LatteLogger.d(TAG, "checkGoodsState exception...");
            ex.printStackTrace();
        }
    }

    private static String getLineString(String scanId, String channelListStr) {
        if (ThreeGoReceiver.type.equals(OpenDoorType.BUYER.getType())) {
            for (byte j = 1; j < ConstValue.LAYERNUM; j++) {
                channelListStr += goodsDevice.goodsRangeCheckCloseDoor(j, (byte) 0x03,
                        scanId, ConstValue.LINENUM);
//                            goodsLineMsgList = getGoodsLineMsg(goodsLineMsgList, j,
//                                    GoodsLineMsg.BUY_GOODS);
//                            channelListStr = JSON.toJSONString(goodsLineMsgList);
                if ("".equals(channelListStr)) {
                    channelListStr += goodsDevice.goodsRangeCheckCloseDoor(j, (byte) 0x03,
                            scanId, ConstValue.LINENUM);
//                                goodsLineMsgList = getGoodsLineMsg(goodsLineMsgList, j,
//                                        GoodsLineMsg.BUY_GOODS);
//                                channelListStr = JSON.toJSONString(goodsLineMsgList);
                }
            }
        } else {
            for (byte j = 1; j < ConstValue.LAYERNUM; j++) {
                channelListStr += goodsDevice.goodsRangeCheckCloseDoor(j, (byte) 0x05,
                        scanId, ConstValue.LINENUM);
//                            goodsLineMsgList = getGoodsLineMsg(goodsLineMsgList, j,
//                                    GoodsLineMsg.BUY_GOODS);
//                            channelListStr = JSON.toJSONString(goodsLineMsgList);
                if ("".equals(channelListStr)) {
                    channelListStr += goodsDevice.goodsRangeCheckCloseDoor(j, (byte) 0x05,
                            scanId, ConstValue.LINENUM);
//                                goodsLineMsgList = getGoodsLineMsg(goodsLineMsgList, j,
//                                        GoodsLineMsg.BUY_GOODS);
//                                channelListStr = JSON.toJSONString(goodsLineMsgList);
                }
            }
        }
        return channelListStr;
    }

    private static boolean isOpeSpeak = true;

    private static void speakOpenStr() {
        if (ThreeGoReceiver.type.equals(OpenDoorType.BUYER.getType())) {
            if (!mediaPlayControl.isPlaying()) {
                mediaPlayControl.play(MediaPath.oldPath);
            }
        } else {
            if (isOpeSpeak) {
                BaiduTTSSpeakUtil.getInstance().speak("请补货");
                isOpeSpeak = false;
            }
        }
    }

    /**
     * 检查电磁锁状态
     *
     * @param scanId
     * @param scanType
     * @return
     */

    private static int checkDoorState(String scanId, String scanType) {
        int doorPullSuccess = 0;
        try {
            int leftDoorState = 0;

            int i = 0;
            while (i <= 5) {
                leftDoorState = MainActivity.eleLockDevice.CheckEleLockState();
                LatteLogger.d("doorstatus", leftDoorState);
                if (leftDoorState == 2 || leftDoorState == 3) {
                    doorPullSuccess = 1;
                    break;
                }

                if (i == 5) {
                    MainActivity.eleLockDevice.OpenOrCloseLeftLock(2);
                    if (ConstValue.DOORTYPE.equals(DoorType.DOUBLEDOOR.getDoorType())) {
                        MainActivity.eleLockDevice.OpenOrCloseRightLock(2);
                    }
                    postCloseDoorMsgMul(scanId, scanType, "");
                    mediaPlayControl.play(MediaPath.closePath);
                    doorPullSuccess = -1;
                }

                i++;
                Thread.sleep(1000L);

            }
        } catch (Exception e) {
            e.printStackTrace();
            doorPullSuccess = -1;
        }
        return doorPullSuccess;
    }

    /**
     * 发送关门反馈信息
     *
     * @param scanId
     * @param scanType
     * @param channelListStr
     */
    private static void postCloseDoorMsgMul(String scanId, String scanType, String channelListStr) {
        try {
            if (ThreeGoReceiver.type.equals(OpenDoorType.BUYER.getType())) {
                PARAMMAP.put("userScanId", scanId);
            } else {
                PARAMMAP.put("staffScanId", scanId);
                PARAMMAP.put("scanStatus", "0");
            }

            PARAMMAP.put("closeStatus", "1");
            if ("".equals(scanType) || scanType == null) {
                LatteLogger.d(TAG, "scanType null.......");
            } else {
                PARAMMAP.put("scanType", scanType);
            }

            PARAMMAP.put("channelListStr", channelListStr);
            LatteLogger.d("货道信息：", channelListStr);
            if (ThreeGoReceiver.type.equals(OpenDoorType.BUYER.getType())) {
                if (IsInternet.checkNetwork(context)) {
                    postUserCloseDoor();
                } else {
                    rePostUserCloseDoorMsg();
                }
            } else {
                if (IsInternet.checkNetwork(context)) {
                    postOpeCloseDoor();
                } else {
                    rePostOpCloseDoorMsg();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 每隔一秒检测一次网络状态，直至运维人员关门反馈发送成功
     */
    private static void rePostOpCloseDoorMsg() {
        executorService.execute(() -> {
            try {
                while (true) {
                    if (IsInternet.checkNetwork(context)) {
                        postOpeCloseDoor();
                        break;
                    }
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 每隔一秒检测一次网络状态，直至用户关门反馈发送成功
     */
    private static void rePostUserCloseDoorMsg() {
        executorService.execute(() -> {
            try {
                while (true) {
                    if (IsInternet.checkNetwork(context)) {
                        postUserCloseDoor();
                        break;
                    }
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });
    }

    /**
     * 发送运维人员关门反馈信息
     */
    private static void postOpeCloseDoor() {
        OkHttpClientManager.getInstance().postAsync(Constants.getStaffclose(), HttpConstants.close_door,
                PARAMMAP, new OkHttpClientManager.HttpCallback() {
                    @Override
                    public void onSuccess(String result, int code) {
                        LatteLogger.i("opmsg:", "订单推送成功" + PARAMMAP.toString());
                        ThreeGoReceiver.resetOpenDoorTime();
                    }

                    @Override
                    public void onStart(int code) {
                    }

                    @Override
                    public void onFailure(int code) {
                        ThreeGoReceiver.resetOpenDoorTime();
                    }
                });
    }

    /**
     * 发送用户关门反馈信息
     */
    private static void postUserCloseDoor() {
        OkHttpClientManager.getInstance().postAsync(Constants.getClose(), HttpConstants.close_door,
                PARAMMAP, new OkHttpClientManager.HttpCallback() {
                    @Override
                    public void onSuccess(String result, int code) {
                        LatteLogger.i("opmsg:", "订单推送成功" + PARAMMAP.toString());
                        ThreeGoReceiver.resetOpenDoorTime();
                    }

                    @Override
                    public void onStart(int code) {

                    }

                    @Override
                    public void onFailure(int code) {
                        ThreeGoReceiver.resetOpenDoorTime();
                    }
                });
    }

    private static int getLocFlag() {
        int locFlag;
        if (ConstValue.DOORTYPE.equals(DoorType.SINGLEDOOR.getDoorType())) {
            locFlag = eleLockDevice.OpenOrCloseLeftLock(1);
            mediaPlayControl.play(MediaPath.openPath);
        } else {
            int leftFlag = MainActivity.eleLockDevice.OpenOrCloseLeftLock(1);
            int rightFlag = MainActivity.eleLockDevice.OpenOrCloseRightLock(1);
            BaiduTTSSpeakUtil.getInstance().speak("请拉开柜门,进行补货");
            if (leftFlag == 1 && rightFlag == 1) {
                locFlag = 1;
            } else {
                locFlag = -2;
            }
        }
        for (byte i = 1; i < ConstValue.LAYERNUM; i++) {
            goodsDevice.goodsrangecheck_opendoor(i, ConstValue.LINENUM);
        }
        return locFlag;
    }
}
